
var vm = new Vue({
    el: '#app',
    data: function () {
        return {
            pagename: "计划排产",
            common_fn: null,
            userinfo: null,
            loading: false,
            maxScreenHeight: 0,
            mainTable_maxHeight: 0,
            orderData: [],//订单
            selectedOrderID: "",
            selectedOrderNo: "",
            selectedProductionSchedule: "",
            MBomDefined: [],  //界面显示的MBom结构
            APStemp: [],
            workshopID: "", //人员所属车间ID
            teamID: "",//人员所属班组ID
            loading_apsschedule: false,
            loading_apsrelease: false,
        }
    },
    methods: {
        //获取已建订单
        getOrders: function () {
            var self = this;
            var filters = [{
                "classFlag": 1,
                "classType": "MesOrderSheet",
                "propName": "state",
                "op": 4,
                "propValue": "0",
                "propValue2": "",
                "logic": 0,
                "leftSplitter": 0,
                "rightSplitter": 0,
                "bAddWhereClauseFlag": true
            }];
            self.loading = true;
            self.common_fn.queryObject("MesOrderSheet", filters, self.userinfo, function (response) {
                if (response.resFlag == 0) {
                    for (i = response.result.length - 1; i >= 0; i--) {
                        response.result[i].properties.state == 0 ? response.result[i].properties['state_name'] = '待审核' : response.result[i].properties.state == 1 ? response.result[i].properties['state_name'] = '审核中' : response.result[i].properties['state_name'] = '已发布';
                        response.result[i].properties.deliverydate = response.result[i].properties.deliverydate.split(' ')[0];
                        response.result[i].properties.creationdate = response.result[i].properties.creationdate.split(' ')[0]; //APP加
                        response.result[i].properties.orderquantity = Number(response.result[i].properties.orderquantity);
                        self.orderData.push({
                            "id": response.result[i].id,
                            "name": response.result[i].properties.name,
                        })
                    }
                    self.orderData = response.result;
                    if (self.orderData.length !== 0) {
                        self.selectedOrderNo = self.orderData[self.orderData.length - 1].properties.orderno;
                        self.selectedOrderID = self.orderData[self.orderData.length - 1].id
                        self.getMBom(self.selectedOrderID);
                    }
                } else {
                    notify(response.errMsg, 'error')
                }
                self.loading = false;
            })
        },
        //选择某个订单
        selectOrder: function () {
            this.getMBom(this.selectedOrderID)
        },
        //递归循环获得所需MBom
        getMBomDefined: function (target) {
            var self = this;
            target.forEach(function (item) {
                if (item.entity.type.toLowerCase() == "plmpart") {
                    for (var i = 0; i < item.children.length; i++) {
                        if (item.children[i].entity.type.toLowerCase() == "messemifinished") {
                            self.MBomDefined.push({
                                "materialno": item.entity.properties.materialno,
                                "identityno": item.entity.properties.identityno,
                                "name": item.entity.properties.name,
                                "indexno": item.children[i].relation.properties.indexno, //工序号
                                "qcpname": item.children[i].entity.properties.name,  //工序名称
                                "startdate": item.children[i].entity.properties.startdate,
                                "enddate": item.children[i].entity.properties.enddate,
                                "orderquantity": item.children[i].entity.properties.orderquantity,//数量
                                "assemblyunit": item.children[i].entity.properties.assemblyunit,  //单位
                                "process_objid": item.children[i].entity.properties.process_objid  //工序对象标识  
                            })
                        }
                    }
                    self.getMBomDefined(item.children)
                }
            }
            );
        },
        //获取某个批次即某订单下的MBOM
        getMBom: function (orderID) {
            var self = this;
            //获取批次计划ID
            var entryObjects = [{
                "id": orderID,
                "type": "MesOrderSheet"
            }]
            self.common_fn_school.QueryObjectsGraph(self.userinfo.user, null, entryObjects, ["MesOrderSheetProduct"], function (response) {
                if (response.resFlag == 0) {
                    self.selectedProductionSchedule = response.result.roots[0].children[0].entity;
                    var productionScheduleId = response.result.roots[0].children[0].entity.id;
                    var productionScheduvarype = response.result.roots[0].children[0].entity.type
                    //获取批次计划Snapshot
                    self.common_fn_school.GetCurrentSnapshot(productionScheduleId, productionScheduvarype, 3, function (response) {
                        if (response.resFlag == 0) {
                            var productionScheduleSnapshotId = response.result.id;
                            //获取MBom
                            var productionScheduleSnapshots = [{
                                "type": "SYSSNAPSHOT",
                                "id": productionScheduleSnapshotId
                            }]
                            var entryObjects =
                                [{
                                    "id": productionScheduleId,
                                    "type": "MesProductionSchedule"
                                }]
                            self.common_fn_school.QueryObjectsGraph(self.userinfo.user, productionScheduleSnapshots, entryObjects, ["MesProductPartLink", "MesPartPartLink", "MesPartSemifinished", "MesSemifinishedProcess"], function (response) {
                                if (response.resFlag == 0) {
                                    self.MBomDefined = [];//清空
                                    self.getMBomDefined(response.result.roots[0].children);
                                }
                            })
                        }
                    })
                }
            })
        },

        //APS排产
        startAPS: function () {
            var self = this;
            self.loading_apsschedule = true;
            var d = new Date();
            self.selectedProductionSchedule.properties.fixedstartdate = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
            self.selectedProductionSchedule.properties.startdate = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
            var param = [
                self.selectedProductionSchedule
            ]
            self.common_fn_school.Schedule_AutoSchedule(param, self.userinfo.user, function (response) {
                if (response.resFlag == 0) {
                    if (response.result.items["0"].itemObjects["0"].type == "MesApsError") {
                        notify(response.result.items["0"].itemObjects["0"].properties.apserrors, 'error')
                    } else {
                        //排产数据保存到数据库
                        var APStemp = []
                        for (var i = 0; i < response.result.items.length; i++) {
                            APStemp.push(response.result.items[i].itemObjects[0]);
                            APStemp[i].properties["*Start"] = response.result.items[i].itemObjects[0].properties.starttime;
                            APStemp[i].properties["*End"] = response.result.items[i].itemObjects[0].properties.endtime;
                        }
                        var param = APStemp
                        self.common_fn_school.SaveMonthScheduleTable(param, self.userinfo.user, function (response) {
                            if (response.resFlag == 0) {
                                //保存完成后，从后台取数据
                                var filters = [];
                                self.common_fn.queryObject("MesSemifinished", filters, self.userinfo, function (response) {
                                    if (response.resFlag == 0) {
                                        //时间
                                        for (var i = 0; i < response.result.length; i++) {
                                            for (var j = self.MBomDefined.length - 1; j >= 0; j--) {
                                                if (response.result[i].properties.process_objid == self.MBomDefined[j].process_objid) {
                                                    self.MBomDefined[j].startdate = response.result[i].properties.startdate;
                                                    self.MBomDefined[j].enddate = response.result[i].properties.enddate
                                                }
                                            }

                                        }
                                        self.loading_apsschedule = false;
                                        message("已成功排产！", 'success')
                                    } else {
                                        notify(response.errMsg, 'error')
                                    }
                                })
                            } else {
                                notify(response.errMsg, 'error')
                            }
                        })
                    }
                } else {
                    self.loading_apsschedule = false;
                    notify(response.errMsg, 'error')
                }
            })
        },

        //计划发布
        releaseAPS: function () {
            var self = this;
            self.loading_apsrelease = true;
            var param = {
                "appName": "mes",
                "sql": "update MES_SEMIFINISHED set Workshop_OBJID = " + self.workshopID
            };
            self.common_fn.sqlFn(param, function (response) {
                if (response.resFlag == 0) {
                    //计划提交审核
                    self.common_fn_school.ProductionSheduleStateChange(self.selectedProductionSchedule, 1, self.userinfo.user, function (response) {
                        if (response.resFlag == 0) {
                            //计划审核发布
                            self.common_fn_school.ProductionSheduleStateChange(response.result, 3, self.userinfo.user, function (response) {
                                if (response.resFlag == 0) {
                                    //修改订单状态为1
                                    var param = {
                                        "appName": "mes",
                                        "sql": "update MES_OrderSheet set state = 1 where objid = " + self.selectedOrderID
                                    }
                                    self.common_fn.sqlFn(param, function (response) {
                                        if (response.resFlag == 0) {
                                            //获取当前批次计划的snaphost
                                            //发布车间计划
                                            var param = {
                                                "appName": "mes",
                                                "sql": "select * from Mes_SemiFinished where Product_OBJID = " + self.selectedProductionSchedule.id
                                            }
                                            self.common_fn.sqlFn(param, function (response) {
                                                if (response.resFlag == 0) {
                                                    var semifinisheds = [];
                                                    var snapshots = [];
                                                    var teamObjids = [];
                                                    for (var i = 0; i < response.result.length; i++) {
                                                        semifinisheds.push({
                                                            "id": response.result[i].id,
                                                            "properties": {},
                                                            "type": "MesSemiFinished"
                                                        })
                                                        snapshots.push({
                                                            "id": self.productionScheduleSnapshotId,
                                                            "properties": {},
                                                            "type": "SysSnapshot"
                                                        })
                                                        teamObjids.push(self.teamID)
                                                    }
                                                    self.common_fn_school.WorkShopPlanBatchPublish(self.userinfo.user, semifinisheds, snapshots, teamObjids, function (response) {
                                                        if (response.resFlag == 0) {
                                                            self.MBomDefined = [];
                                                            self.loading_apsrelease = false;
                                                            message('计划已成功发布！请前往派工！', 'success')
                                                        }
                                                    })
                                                } else {
                                                    notify(response.errMsg, 'error')
                                                    self.loading_apsrelease = false;
                                                }
                                            })
                                        }
                                    })
                                } else {
                                    notify(response.errMsg, 'error')
                                    self.loading_apsrelease = false;
                                }
                            })
                        } else {
                            notify("请先排产，后发布！", 'error')
                            self.loading_apsrelease = false;
                        }
                    })
                }
            })
        },
        // 查找当前登录人所在车间下所有班组
        findTeams: function () {
            var self = this;
            self.common_fn.queryRelatedGraph(self.userinfo.user, 'MesPersonOfWorkShop', self.userinfo, function (response) {
                if (response.resFlag == 0) {
                    self.workshopID = response.result[0].entity.id;  //一个车间
                    self.common_fn.queryRelatedGraph(response.result[0].entity, 'MesWorkShopWithTeam', self.userinfo, function (res1) {
                        if (res1.resFlag == 0) {
                            self.teamID = res1.result[0].entity.id;
                        } else {
                            notify(res1.errMsg, 'error')
                        }
                    })
                } else {
                    notify(response.errMsg, 'error')
                }
            })
        },




    },
    mounted: function () {
        var self = this;
        self.common_fn = new common_fn();
        self.common_fn_school = new common_fn_school();
        self.common_fn.init(function () {
            self.common_fn.UserInfo(function (response) {
                if (response.user == null) {
                    window.location.href = 'login.html?redirect=teamplan.html';
                }
                self.userinfo = response;
                self.common_fn.CheckFunction(self.userinfo, 'mes', 'mes', 'TeamPlanMgr', '', '', 'teamplan', function () { })
                self.common_fn.queryObject('SysPerson', [], self.userinfo, function (res1) {
                    if (res1.resFlag == 0) {
                        // for (var k = 0; k < res1.result.length; k++) {
                        //     self.allpeople[res1.result[k].id] = res1.result[k];
                        // }
                        self.orderData = [];
                        self.getOrders();
                        self.findTeams();
                    } else {
                        notify(res1.errMsg, 'error')
                    }
                })
            })
        });
        self.maxScreenHeight = window.screen.height * 0.7;
    }
})
window.onload = function () {
    if (vm.mainTable_maxHeight != null || vm.mainTable_maxHeight != undefined) {
        window.setTimeout(function () {
            vm.mainTable_maxHeight = $(window).height() - 150;
        }, 100)
    }
}
